package com.example.second.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.second.Dao.IStockDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.spec.OAEPParameterSpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class StockServiceImpl implements IStockService{

    @Autowired
    IStockDao iStockDao;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //跨服务
    @Autowired
    RestTemplate restTemplate;

    public Map<String,Object> getStockList(){
        List<Map<String,Object>> list = iStockDao.getStockList();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        if(list.isEmpty())  {
            resultMap.put("result", false);
            resultMap.put("msg", "no stock infomation");
            return resultMap;
        }
        resultMap = getLimitPolicy(list);
        resultMap.put("sku_list", list);
        return resultMap;
    }

    public Map<String,Object> getStock(String sku_id){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        if(sku_id==null||sku_id.equals("")){
            resultMap.put("result", false);
            resultMap.put("msg", "canshuyouwu");
            return resultMap;
        }

        //先去redis找商品详情，如果找不到再去读MySQL数据库
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        if (stringRedisTemplate.opsForValue().get("SKU_" + sku_id)!=null){
            list.add(JSON.parseObject(stringRedisTemplate.opsForValue().get("SKU_" + sku_id), Map.class));
            resultMap = getLimitPolicy(list);
        }else {
            list = iStockDao.getStock(sku_id);
        }

        if(list.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "no sku found");
            return resultMap;
        }
        resultMap.put("sku_list", list);
        return resultMap;
    }

    public Map<String,Object> insertLimitPolicy(Map<String,Object> policyInfo)  {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        if(policyInfo==null||policyInfo.isEmpty()){
            resultMap.put("result", false);
            resultMap.put("msg", "政策信息有误");
            return resultMap;
        }
        Boolean  result = iStockDao.insertLimitPolicy(policyInfo);
        if(!result){
            resultMap.put("result", false);
            resultMap.put("msg","政策信息插入数据库失败");
            return resultMap;
        }

        //diff为缓存有效期，过期数据被物理删除
        long diff = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String now = restTemplate.getForObject("http://time-server/gettime", String.class);
        try {
            Date endtime = simpleDateFormat.parse(policyInfo.get("end_time").toString());
            Date nowtime = simpleDateFormat.parse(now );
            diff = (endtime.getTime()-nowtime.getTime())/1000;
            if(diff<=0){
                resultMap.put("result", false);
                resultMap.put("msg", "结束时间不能小于当前时间");
                return resultMap;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //往redis里存政策信息，过期自动删除。注意提前打开redis服务，即redis-server
        String policy = JSON.toJSONString(policyInfo);
        stringRedisTemplate.opsForValue().set("LIMIT_POLICY_"+policyInfo.get("sku_id").toString(), policy,
                diff, TimeUnit.SECONDS );
        //往redis里存商品详情
        List<Map<String,Object>> sku_info = iStockDao.getStock(policyInfo.get("sku_id").toString());
        String sku = JSON.toJSONString(sku_info.get(0));
        stringRedisTemplate.opsForValue().set("SKU_"+policyInfo.get("sku_id").toString(), sku, diff, TimeUnit.SECONDS);

        resultMap.put("result", true);
        resultMap.put("msg", "成功写入政策信息");
        return resultMap;
    }

    private Map<String,Object> getLimitPolicy(List<Map<String,Object>> skuList){

        Map<String,Object>  resultMap = new HashMap<String, Object>();
        for(Map<String,Object> skuMap:skuList){
            String policy = stringRedisTemplate.opsForValue().get("LIMIT_POLICY_"+skuMap.get("sku_id").toString());

            if(policy!=null&&!policy.equals("")){
                Map<String,Object> policyMap = JSON.parseObject(policy,Map.class);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date begin = simpleDateFormat.parse(policyMap.get("begin_time").toString());
                    Date end = simpleDateFormat.parse(policyMap.get("end_time").toString());
                    String nowString = restTemplate.getForObject("http://time-server/gettime", String.class);
//                    String nowString = restTemplate.getForObject("http://localhost:8000/gettime", String.class);
                    Date now = simpleDateFormat.parse(nowString);

                    if(now.getTime()>=begin.getTime()&&now.getTime()<=end.getTime()){
                        skuMap.put("limit_price", policyMap.get("price"));
                        skuMap.put("limit_quanty",policyMap.get("quanty"));
                        skuMap.put("limit_begin",policyMap.get("begin_time"));
                        skuMap.put("limit_end",policyMap.get("end_time"));
                        skuMap.put("now_time",nowString);
                    }
                }catch (Exception exception){
                }
            }
        }
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }
}
